<template>
  <div>
    <!--  面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path :'/goods'}">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!--  卡片区域  -->
    <el-card>
      <!--  添加商品信息提示  -->
      <el-alert center title="添加商品信息" type="info" show-icon></el-alert>
      <!--  顶部步骤条 -->
      <el-steps align-center :active="activeNum" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form label-position="top" :model="baseForm" :rules="baseRules" ref="baseFormRef" label-width="100px">
        <!-- 侧边Tab 标签 -->
        <el-tabs @tab-click="tabClick" tab-position="left">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input @blur="isDis" v-model="baseForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input @blur="isDis" v-model="baseForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input @blur="isDis" v-model="baseForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input @blur="isDis" v-model="baseForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <span>选择商品分类：</span>
              <el-cascader v-model="selectedCate" :options="cateList"
                           :props="{ expandTrigger: 'hover',value:'cat_id',label:'cat_name',children:'children' }"
                           @change="handleChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane :disabled="isDisabled" label="商品参数">
            <el-form-item :key="i" :label="item.attr_name" v-for="(item,i) in getParamsList">
              <el-checkbox-group v-model="item.attr_vals" size="small">
                <el-checkbox :key="i1" v-for="(item1,i1) in item.attr_vals" :label="item1"
                             border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane :disabled="isDisabled" label="商品属性">
            <el-form-item :key="i" :label="item.attr_name" v-for="(item,i) in getParamsList">
              <el-checkbox-group v-model="item.attr_vals" size="small">
                <el-checkbox :key="i1" v-for="(item1,i1) in item.attr_vals" :label="item1"
                             border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane :disabled="isDisabled" label="商品图片">
            <el-upload :on-preview="onPreview" :on-remove="onRemove" :on-success="onSuccess" :headers="headersObj"
                       action="http://timemeetyou.com:8889/api/private/v1/upload"
                       list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane :disabled="isDisabled" label="商品内容">
            <quill-editor v-model="baseForm.goods_introduce"></quill-editor>
            <el-button @click="addForm" type="primary">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="图片预览" :visible.sync="picDialogVisible" width="50%">
      <img style="width: 100%" :src="preUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "AddGoods",
    data() {
      return {
        preUrl: '',
        picDialogVisible: false,
        headersObj: {
          Authorization: window.sessionStorage.getItem('token')
        },
        getParamsList: [],
        isDisabled: true,
        baseForm: {
          goods_name: '',
          goods_price: 0,
          goods_weight: 0,
          goods_number: 0,
          goods_introduce:'',
          pics: [],
          goods_cat:[],
          attrs:[],
        },
        baseRules: {
          goods_name: [
            {required: true, message: '请输入商品名称', trigger: 'blur'}
          ],
          goods_price: [
            {required: true, message: '请输入商品价格', trigger: 'blur'}
          ],
          goods_weight: [
            {required: true, message: '请输入商品重量', trigger: 'blur'}
          ],
          goods_number: [
            {required: true, message: '请输入商品数量', trigger: 'blur'}
          ]
        },
        activeNum: 0,
        cateList: [],
        selectedCate: []
      }
    },

    created() {
      this.getCateList();
    },

    methods: {
      /*  添加商品 */
      async addForm(){
        /*  处理提交需要的goods_cat*/
        this.baseForm.goods_cat = this.selectedCate;
        this.baseForm.goods_cat = this.baseForm.goods_cat.join(',');
        /*  处理动态参数和静态属性   */
        this.getParamsList.forEach(item=>{
          const newInfo = {
            attr_value:item.attr_vals.join(' '),
            attr_id:item.attr_id
          }
          this.baseForm.attrs.push(newInfo);
        })
       /*console.log(this.baseForm);*/
        /*  请求提交  */
        const {data: res}= await this.$http.post('goods',this.baseForm);
        if (res.meta.status === 201){
          this.$router.push('/goods');
          this.$message.success('添加成功');
        }else {
          this.$message.error('添加失败');
        }

      },
      /*  获取地址  */
      onPreview(file) {
        this.preUrl = file.response.data.url;
        this.picDialogVisible = true;
      },
      /*  从数据列表删除该图片的临时路径 */
      onRemove(file) {
        const picPath = file.response.data.tmp_path;
        const index = this.baseForm.pics.findIndex(i => i === picPath);
        this.baseForm.pics.splice(index, 1);
      },
      /*  获取临时路径 存储到数据列表  */
      onSuccess(file) {
        const picInfo = {pic: file.data.tmp_path};
        this.baseForm.pics.push(picInfo);
      },
      /* 失去焦点时触发   */
      isDis() {
        this.$refs.baseFormRef.validate(valid => {
          if (!valid) {
            this.isDisabled = true;
            return;
          } else {
            if (this.selectedCate.length !== 3) {
              return;
            }
            this.isDisabled = false;
          }
        })
      },
      /*  监听商品分类变化  */
      handleChange() {
        if (this.selectedCate.length !== 3) {
          this.selectedCate = [];
          this.isDisabled = true;
        } else {
          this.isDis()
        }
      },
      /*  侧边tab点击事件   */
      async tabClick(data) {
        this.activeNum = parseInt(data.index);
        //  获取商品参数数据
        if (this.activeNum === 1) {
          const {data: paraRes} = await this.$http.get(`categories/${this.selectedCate[2]}/attributes`, {
            params: {
              sel: 'many'
            }
          });
          if (paraRes.meta.status === 200) {
            paraRes.data.forEach(item => {
              item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ');
            })
          } else {
            this.$message.error('参数获取失败');
          }
          /*   console.log(paraRes.data);*/
          this.getParamsList = paraRes.data;
          /*  获取商品属性数据  */
        } else if (this.activeNum === 2) {
          const {data: attrRes} = await this.$http.get(`categories/${this.selectedCate[2]}/attributes`, {
            params: {
              sel: 'only'
            }
          });
          if (attrRes.meta.status === 200) {
            attrRes.data.forEach(item => {
              item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ');
            })
          } else {
            this.$message.error('参数获取失败');
          }
          this.getParamsList = attrRes.data;
        }
      },
      /*  获取商品分类列表数据  */
      async getCateList() {
        const {data: res} = await this.$http.get('categories');
        if (res.meta.status === 200) {
          this.cateList = res.data;
        } else {
          this.$message.error('获取商品分类列表失败')
        }

      }
    }
  }
</script>

<style scoped>
  .quill-editor {
    margin-bottom: 75px;
    height: 300px;
  }
</style>
